import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { formatToBeijingTime } from '../utils/timeUtils';

const TaskAuditPage = () => {
  const [auditRecords, setAuditRecords] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [filterTaskId, setFilterTaskId] = useState('');

 const fetchAuditRecords = async (taskId = '') => {
  setLoading(true);
  setError('');
  
  try {
    let url = '/api/tasks/audit';
    if (taskId && taskId.trim() !== '') {
      url += `/${encodeURIComponent(taskId.trim())}`;
    }
    
    // 使用通用请求函数
    const response = await fetch(`http://localhost:3001${url}`);
    const result = await response.json();
    
    if (result.success) {
      setAuditRecords(result.data || []);
    } else {
      throw new Error(result.message || '获取审计记录失败');
    }
  } catch (err) {
    console.error('获取审计记录失败:', err);
    setError('获取审计记录失败: ' + err.message);
  } finally {
    setLoading(false);
  }
};

  useEffect(() => {
    fetchAuditRecords();
  }, []);

  const handleRefresh = () => {
    if (filterTaskId) {
      fetchAuditRecords(filterTaskId);
    } else {
      fetchAuditRecords();
    }
  };

  const handleFilter = (e) => {
    e.preventDefault();
    fetchAuditRecords(filterTaskId);
  };

  const getStatusText = (value) => {
    if (value === null || value === undefined) return 'N/A';
    return value === 1 ? '已下发' : '未下发';
  };

  const getTypeText = (type) => {
    switch (type) {
      case 'INSERT': return '插入';
      case 'UPDATE': return '更新';
      default: return type;
    }
  };

  return (
    <div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        marginBottom: '20px' 
      }}>
        <h2>任务状态变更审计</h2>
        <div>
          <Link to="/" style={{
            padding: '8px 16px',
            backgroundColor: '#6c757d',
            color: 'white',
            textDecoration: 'none',
            borderRadius: '4px',
            marginRight: '10px'
          }}>
            返回主页
          </Link>
          <button
            onClick={handleRefresh}
            disabled={loading}
            style={{
              padding: '8px 16px',
              backgroundColor: '#007bff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: loading ? 'not-allowed' : 'pointer'
            }}
          >
            {loading ? '刷新中...' : '刷新'}
          </button>
        </div>
      </div>

      {/* 过滤器 */}
      <form onSubmit={handleFilter} style={{ 
        marginBottom: '20px',
        padding: '15px',
        backgroundColor: '#f8f9fa',
        borderRadius: '5px'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <label>任务ID:</label>
          <input
            type="text"
            value={filterTaskId}
            onChange={(e) => setFilterTaskId(e.target.value)}
            placeholder="输入任务ID进行过滤"
            style={{
              padding: '5px 10px',
              borderRadius: '3px',
              border: '1px solid #ccc'
            }}
          />
          <button
            type="submit"
            style={{
              padding: '5px 15px',
              backgroundColor: '#28a745',
              color: 'white',
              border: 'none',
              borderRadius: '3px',
              cursor: 'pointer'
            }}
          >
            过滤
          </button>
          <button
            type="button"
            onClick={() => {
              setFilterTaskId('');
              fetchAuditRecords();
            }}
            style={{
              padding: '5px 15px',
              backgroundColor: '#ffc107',
              color: 'black',
              border: 'none',
              borderRadius: '3px',
              cursor: 'pointer'
            }}
          >
            清除
          </button>
        </div>
      </form>

      {error && (
        <div style={{ 
          padding: '10px', 
          backgroundColor: '#f8d7da', 
          color: '#721c24', 
          borderRadius: '5px',
          marginBottom: '20px'
        }}>
          {error}
        </div>
      )}

      <div style={{ 
        overflowX: 'auto',
        border: '1px solid #dee2e6',
        borderRadius: '5px'
      }}>
        <table style={{ 
          width: '100%', 
          borderCollapse: 'collapse',
          minWidth: '800px'
        }}>
          <thead>
            <tr style={{ backgroundColor: '#e9ecef' }}>
              <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #dee2e6' }}>ID</th>
              <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #dee2e6' }}>任务ID</th>
              <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #dee2e6' }}>任务编号</th>
              <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #dee2e6' }}>货位</th>
              <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #dee2e6' }}>变更类型</th>
              <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #dee2e6' }}>原状态</th>
              <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #dee2e6' }}>新状态</th>
              <th style={{ padding: '12px', textAlign: 'left', border: '1px solid #dee2e6' }}>变更时间</th>
            </tr>
          </thead>
          <tbody>
            {auditRecords.length > 0 ? (
              auditRecords.map((record) => (
                <tr key={record.id} style={{ 
                  backgroundColor: record.id % 2 === 0 ? '#fff' : '#f8f9fa'
                }}>
                  <td style={{ padding: '10px', border: '1px solid #dee2e6' }}>{record.id}</td>
                  <td style={{ padding: '10px', border: '1px solid #dee2e6' }}>{record.task_id}</td>
                  <td style={{ padding: '10px', border: '1px solid #dee2e6' }}>{record.Task_No || 'N/A'}</td>
                  <td style={{ padding: '10px', border: '1px solid #dee2e6' }}>
                    {record.Unload_Line && record.Unload_Col && record.Unload_Layer 
                      ? `排${record.Unload_Line} 列${record.Unload_Col} 层${record.Unload_Layer}`
                      : 'N/A'}
                  </td>
                  <td style={{ padding: '10px', border: '1px solid #dee2e6' }}>
                    <span style={{
                      padding: '3px 8px',
                      borderRadius: '3px',
                      backgroundColor: record.change_type === 'INSERT' ? '#28a745' : '#007bff',
                      color: 'white',
                      fontSize: '12px'
                    }}>
                      {getTypeText(record.change_type)}
                    </span>
                  </td>
                  <td style={{ padding: '10px', border: '1px solid #dee2e6' }}>
                    <span style={{
                      padding: '3px 8px',
                      borderRadius: '3px',
                      backgroundColor: record.old_is_issued === 1 ? '#28a745' : '#ffc107',
                      color: 'white',
                      fontSize: '12px'
                    }}>
                      {getStatusText(record.old_is_issued)}
                    </span>
                  </td>
                  <td style={{ padding: '10px', border: '1px solid #dee2e6' }}>
                    <span style={{
                      padding: '3px 8px',
                      borderRadius: '3px',
                      backgroundColor: record.new_is_issued === 1 ? '#28a745' : '#ffc107',
                      color: 'white',
                      fontSize: '12px'
                    }}>
                      {getStatusText(record.new_is_issued)}
                    </span>
                  </td>
                  <td style={{ padding: '10px', border: '1px solid #dee2e6' }}>
                    {formatToBeijingTime(record.changed_at)}
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan="8" style={{ 
                  padding: '20px', 
                  textAlign: 'center', 
                  border: '1px solid #dee2e6' 
                }}>
                  {loading ? '加载中...' : '暂无审计记录'}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <div style={{ 
        marginTop: '10px',
        fontSize: '14px',
        color: '#6c757d',
        textAlign: 'right'
      }}>
        总计: {auditRecords.length} 条记录
      </div>
    </div>
  );
};

export default TaskAuditPage;